package com.LeeCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 分割回文串
 */

public class Code131 {
    public static void main(String[] args) {
        String s = "aabbbbb";
        System.out.println(new Code131().partition(s));
    }

    public List<List<String>> partition(String s) {
        int n = s.length();
        List<List<String>> res = new ArrayList<>();
        boolean[][] isCircle = new boolean[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(isCircle[i], true);
        }

        for (int i = n - 1; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                isCircle[i][j] = isCircle[i + 1][j - 1] && s.charAt(i) == s.charAt(j);
            }
        }
        backtrack(res, s, new ArrayList<>(), 0, isCircle);
        return res;
    }

    public void backtrack(List<List<String>> res, String s, List<String> cur, int index, boolean[][] isCircle) {
        if (index == s.length()) {
            res.add(new ArrayList<>(cur));
            return;
        }
        for (int j = index; j < s.length(); ++j) {
            if (isCircle[index][j]) {
                cur.add(s.substring(index, j + 1));
                backtrack(res, s, cur, j + 1, isCircle);
                cur.remove(cur.size() - 1);
            }
        }
    }
}
